<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class NewsModel extends CI_Model{
	function __construct(){
		parent::__construct();
	}
	
	function add($data){
		$newdata = array(
			'title'			=> $data['title'],
			'content'		=> $data['content'],
			'companyid'		=> $data['companyid'],
			'time'			=> time()
		);
		
		if ($this->db->insert('news',$newdata)){
			return $this->db->insert_id();
		}
		return false;
	}
	
	function edit($id,$data){
		if (!isset($id) || !is_numeric($id) || ($id < 1)) return false;
		$newdata = array(
			'title'			=> $data['title'],
			'content'		=> $data['content'],
			'companyid'		=> $data['companyid'],
			'time'			=> time()
		);
		$this->db->where('id',$id);
		if ($this->db->update('news',$newdata)){
			return true;
		}
		return false;
	}
	
	function get($id=0){
		if (!is_numeric($id) || ($id < 0)) return false;
		
		if ($id>0){
			$this->db->where('id',$id);
			$q = $this->db->get('news');
			if (!$q->num_rows()) return false;
			$result = $q->first_row();
			
			if ($result->companyid > 0){
				$this->db->where('id',$result->companyid);
				$q = $this->db->get('company');
				if ($q->num_rows()){
					$q = $q->first_row();
					$result->name = $q->name;
				}
			}
			
			return $result;
		}else{
			$this->db->join('company','company.id = news.companyid');
			$this->db->select('news.*,company.name');
			$this->db->order_by('id');
			$q = $this->db->get('news');
			if (!$q->num_rows()) return false;
			
			$result = $q->result();
			
			$this->db->order_by('id');
			$this->db->where('companyid',0);
			$q = $this->db->get('news');
			$result = array_merge($result,$q->result());
			
			return $result;
		}
	}
	
	function delete($ids){
		foreach ($ids as $id){
			$this->db->or_where('id',$id);
		}
		$this->db->delete('news');
		
		return $this->db->affected_rows();
	}
}
?>